// 生成二维码路径的js
import QRCodeImpl from 'qr.js/lib/QRCode'
import ErrorCorrectLevel from 'qr.js/lib/ErrorCorrectLevel'
var qr = {
  getQrUrl: (data) => {
    let size = data.size ? data.size : 160;
    if (typeof data.url === 'undefined') {
      return;
    }
    const qrcode = new QRCodeImpl(-1, ErrorCorrectLevel["L"])
    qrcode.addData(utf16to8(data.url))
    qrcode.make()
    var canvas = document.createElement('canvas');
    canvas.width = 200;
    canvas.height = 200;
    const ctx = canvas.getContext('2d');
    const cells = qrcode.modules;
    const tileW = size / cells.length;
    const tileH = size / cells.length;
    let pr = getBackingStorePixelRatio(ctx);
    const scale = (window.devicePixelRatio || 1) / pr;
    canvas.height = canvas.width = size * scale;
    ctx.scale(scale, scale);
    cells.forEach((row, rdx) => {
      row.forEach((cell, cdx) => {
        ctx.fillStyle = cell ? "#000000" : "#FFFFFF";
        const w = (Math.ceil((cdx + 1) * tileW) - Math.floor(cdx * tileW));
        const h = (Math.ceil((rdx + 1) * tileH) - Math.floor(rdx * tileH));
        ctx.fillRect(Math.round(cdx * tileW), Math.round(rdx * tileH), w, h);
      })
    })
    let imgData = canvas.toDataURL('image/png');
    return imgData;
  },
}

function getBackingStorePixelRatio(ctx) {
  return (
    ctx.webkitBackingStorePixelRatio ||
    ctx.mozBackingStorePixelRatio ||
    ctx.msBackingStorePixelRatio ||
    ctx.oBackingStorePixelRatio ||
    ctx.backingStorePixelRatio ||
    1
  )
}

function utf16to8(str) {
  var out, i, len, c
  out = ''
  len = str.length
  for (i = 0; i < len; i++) {
    c = str.charCodeAt(i)
    if ((c >= 0x0001) && (c <= 0x007F)) {
      out += str.charAt(i)
    } else if (c > 0x07FF) {
      out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F))
      out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F))
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
    } else {
      out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F))
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
    }
  }
  return out
}
export default qr
